package com.durunmin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {


    public static void main(String[] args) throws IOException {

        ServerSocket server = new ServerSocket(2000);

        System.out.println("服务器准备就绪~");
        System.out.println("服务器信息："+server.getInetAddress()+" P: "+server.getLocalPort());

        while(true){

            Socket socket = server.accept();
            ClientHandler clientHandler = new ClientHandler(socket);
            clientHandler.start();

        }
    }

    private static class ClientHandler extends Thread{

        private Socket socket;
        private boolean flag;

        ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("新客户端连接："+socket.getInetAddress()+" P: "+socket.getPort());

            try{

                //得到打印流，用于数据输出；服务器回送数据使用
                PrintStream socketOutput = new PrintStream(socket.getOutputStream());
                //得到输入流，用于读取数据
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                flag = true;
                while(flag){

                    String str = socketInput.readLine();
                    if ("bye".equals(str)){
                        socketOutput.println("bye");
                        flag = false;
                    }else {
                        System.out.println("客户端信息："+str);
                        socketOutput.println("回送："+str.length());
                    }

                }

                socketInput.close();
                socketOutput.close();
            } catch (Exception e){
                System.out.println("连接异常断开");
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("客户端已退出："+socket.getInetAddress()+" P: "+socket.getPort());
        }
    }
}
